package br.dcc.ufmg.xml;

import java.io.File;
import java.io.IOException;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.xml.sax.SAXException;

public class ParserXml {

	private File xmlFile;

	public ParserXml(File xmlFile) {
		super();
		this.xmlFile = xmlFile;
	}

	public boolean isXmlValid() {
		boolean valid = false;
		SchemaFactory factory = SchemaFactory
				.newInstance("http://www.w3.org/2001/XMLSchema");
		Schema schema;
		try {
			schema = factory.newSchema(new StreamSource(getClass()
					.getResourceAsStream("/br/dcc/ufmg/xml/metrics.xsd")));
			Validator validator = schema.newValidator();
			validator.validate(new StreamSource(xmlFile));
			valid = true;
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return valid;
	}

	public Metrics getMetricsFromXml() throws JAXBException {
		JAXBContext jaxbContext = JAXBContext.newInstance(Metrics.class);
		Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
		Metrics metrics = (Metrics) jaxbUnmarshaller.unmarshal(xmlFile);
		return metrics;
	}

}
